<template>
  <div class="cmt-comment">
    <h3>发表评论</h3>
    <textarea placeholder="请输入内容（最多吐槽120字）" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, index) in commentList" :key="item.id">
        <div
          class="cmt-title"
        >第{{index+1}}楼&nbsp;&nbsp;用户：{{ item.name | userForm }}&nbsp;&nbsp;发表时间：{{ item.dateTime | dateFormat }}</div>
        <div class="cmt-body">{{ item.content }}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      commentList: [],
      pageIndex: 1, //默认页码
      pageSize: 10,
      msg: "" //输入的评论内容
    };
  },
  created() {
    this.getCommentList();
  },
  methods: {
    getCommentList() {
      this.$http
        .get(
          "commentList?newsId=" +
            this.id +
            "page=" +
            this.pageIndex +
            "&pageSize=" +
            this.pageSize
        )
        .then(result => {
          //console.log(result);
          if (result.status === 200) {
            this.commentList = this.commentList.concat(result.body.data);
            //this.commentList = result.body.data;
          } else {
            Toast("数据获取失败");
          }
        });
    },
    getMore() {
      this.pageIndex++;
      this.getCommentList();
    },
    postComment() {
      //校验是否为空
      if (this.msg.trim().length === 0) {
        return Toast("评论内容不能为空！");
      }
      //发表评论
      //参数1：请求的URL地址
      //参数2：提交给服务器的数据对象 { content: this.msg }
      //参数3：定义提交时候，表单中数据的格式 { emulateJSON:true}  已经在main.js配置全局了
      this.$http
        .post("addComment?id=" + this.$route.params.id, { content: this.msg.trim() })
        .then(result => {
          if (result.status === 200) {
            //拼接出一个评论对象
            var cmt = {
              id: Date.now(),
              dateTime: Date.now(),
              name: "",
              content: this.msg
            };
            this.commentList.unshift(cmt);
            this.msg=""
          } else {
            Toast("提交失败");
          }
        });
    }
  },
  props: ["id"],
  filters: {
    userForm: function(name) {
      if (!name) return "匿名用户";
      return name;
    }
  }
};
</script>

<style lang="scss" scoped>
.cmt-comment {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 90px;
    margin: 0 auto;
  }
  .cmt-list {
    .cmt-item {
      margin: 5px 0;
      .cmt-title {
        padding: 0 5px;
        background: #ccc;
        font-size: 13px;
        line-height: 30px;
      }
      .cmt-body {
        line-height: 34px;
        text-indent: 20px;
        font-size: 13px;
      }
    }
  }
}
</style>

